<?php

namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

class Cart extends Model
{
    protected $fillable = ['spu_id','sku_id','amount','user_id','created_at','updated_at'];
    public static $error;
    protected $table = 'carts';
    /**前端api
     * 添加购物车
     * $post_data = [
            "goods_id" => 1,
            "sku_id"   => 2,
            "amount"   => 3,
     *      "user_id"  => 1,
        ];
     */
    public function api_add_cart($post_data)
    {
        #检查用户的有效性
        $u_model = User::find($post_data['user_id']);
        if(empty($u_model)){
            self::$error = '该用户不存在';
            return false;
        }

        #检查sku的有效性
        $sku_model = Product::query()
             -> select('products.*')
             -> where('products.goods_id','=',$post_data['goods_id'])
             -> leftJoin('goods','goods.goods_id','=','products.goods_id')
             -> where('product_id','=',$post_data['sku_id'])->first();
        if(empty($sku_model)){
            self::$error = '该商品不存在或已下架';
            return false;
        }

        #检查库存
        if($sku_model->stock < $post_data['amount']){
            self::$error = '商品加购件数(含已加购件数)已超出商品库存!';
            return false;
        }


        #检查用户购物车是否已经添加了该商品
        $user_cart_model =  self::query()
            ->where('spu_id','=',$post_data['goods_id'])
            ->where('sku_id','=',$post_data['sku_id'])
            ->where('user_id','=',$post_data['user_id'])
            ->first();


        #如果已经添加 则将数量累加
        if($user_cart_model){

            #检查添加后是否超过了商品库存
            if($user_cart_model -> amount+$post_data['amount']>$sku_model->stock){
                self::$error = '商品加购件数(含已加购件数)已超出商品库存!';
                return false;
            }

            $user_cart_model -> amount +=  $post_data['amount'];
            if(!$user_cart_model->save()){
                self::$error = '购物车添加失败';
                return false;
            }
        }else{
            #不存在则添加新纪录
            $post_data['spu_id'] = $post_data['goods_id'];
            unset($post_data['goods_id']);
            if(!self::query()->create($post_data)){
                self::$error = '购物车添加失败';
                return false;
            }
        }

        return true;
    }

    /**前端购物车列表
     * @param $uid   int    用户id
     * @return array 购物车列表数据
     */
    public function api_cart_list($uid)
    {
       $query = self::query()
            -> select(
                'price','discount_price','products.name','title',$this->table.'.spu_id AS goods_id',
                        'amount',$this->table.'.sku_id','sku_props_vals.props_id','stock',$this->table.'.id AS cart_id',
                        'sku_props_vals.props_val_id','props_vals.name AS props_val_name','props.name AS props_name'
            )
            -> selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS item_img')->getValue())
            -> where('user_id','=',$uid);

        $list = $this ->_sku_info_join($query,$this->table)->get()->toArray();

        return $this -> _pretty_sku_info_data($list);
    }

    /**前端api更新购物车操作(一次性更新)
     * 添加购物车
     * $post_data = [
         ['goods_id'=>1,'sku_id'=>1,'amount'=>2],
         ['goods_id'=>1,'sku_id'=>2,'amount'=>1],
       ];
     */
    public function api_update_cart($uid,$postData)
    {
        #找出交集的购物车id
        $intersect_id  = self::query()
            ->select('id')
            ->where('user_id','=',$uid)
            ->where(function($query) use($postData){
                foreach($postData as $condition){
                    $query -> orwhere(function($query) use($condition){
                        $query -> where('spu_id','=',$condition['goods_id'])
                               -> where('sku_id','=',$condition['sku_id']);
                    });
                };
            })
            ->get()->toArray();

        #与提交过来的列表进行对比，找出他们之间的差集，进行删除操作
        $intersect_id_arr = array_column($intersect_id,'id');
        if(!empty($intersect_id_arr)){
            self::query()->whereNotIn('id',$intersect_id_arr)->where('user_id','=',$uid)->delete();
        }

        #然后进行更新操作
        foreach($postData as $condition){
            $cart_model = self::query()->where('user_id','=',$uid)
                -> where('spu_id','=',$condition['goods_id'])
                -> where('sku_id','=',$condition['sku_id'])
                -> first();
            if(!empty($cart_model)){
                $cart_model -> spu_id = $condition['goods_id'];
                $cart_model -> sku_id = $condition['sku_id'];
                $cart_model -> amount = $condition['amount'];
                $cart_model -> save();
            }else{
                self::query()->create( [
                        'spu_id'=> $condition['goods_id'],
                        'sku_id'  => $condition['sku_id'],
                        'amount'  => $condition['amount'],
                        'user_id' => $uid
                ]);
            }
        }

        return true;
    }

    /** 前端立即购买和购物车计算统一调用接口
     *   * $post_data = [
                ['sku_id'=>1,'amount'=>2],
                ['sku_id'=>2,'amount'=>1],
           ];
     * @param $uid
     * @param $postData
     */
    public function api_buy_now($uid,$postData)
    {
       $list =  $this -> _sku_info_join(null,'products')
                      -> select(
                           'price','discount_price','products.name','title','products.goods_id',
                              'products.product_id AS sku_id','sku_props_vals.props_id','products.stock AS stock',
                           'sku_props_vals.props_val_id','props_vals.name AS props_val_name','props.name AS props_name'
                       )
                      -> selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS img')->getValue())
                      -> where(function($query) use($postData){
                          foreach($postData as $condition){
                              $query -> orWhere('sku_id','=',$condition['sku_id']);
                          }

                      })
                      -> get()
                      -> toArray();

        foreach($list as &$v){
            foreach($postData as $data){
                if($data['sku_id'] == $v['sku_id']){
                    $v['amount'] = $data['amount'];
                }
            }
        }

        $list =  $this -> _pretty_sku_info_data($list,false);
        if(!$list){
            return false;
        }
        $total_price = 0;
        $total_amount = 0;

        foreach($list as &$v){
            foreach($postData as $data){
                if($data['sku_id'] == $v['sku_id']){
                    $total_amount += $data['amount'];
                }
            }
            $total_price += (isset($v['discount_price']) && $v['discount_price']!='0.00') ? $v['discount_price'] * $v['amount']: $v['price'] * $v['amount'] ;
        }


        return [
            'total_amount'=> $total_amount,
            'goods_list'  => $list,
            'total_price' => $total_price,
            'coupon_list' => (new Coupon())->api_order_canuse_coupon($uid,$total_price),#根据该订单总金额查找可用的优惠券列表和可以使用的优惠力度最大的优惠券以及不可用的优惠券
        ];
    }

    /**购物车数量的添加
     * @param $uid   int   用户id
     * @param $sku_id int  要添加数量的sku_id
     */
    public function api_increment($uid,$sku_id)
    {
       $cart_model = self::query()->where('user_id','=',$uid)->where('sku_id','=',$sku_id)->first();
       $sku_model = Product::find($sku_id);
       if(empty($cart_model) || empty($sku_model)){
           return true;
       }

       #检车库存
       if($cart_model-> amount + 1 >  $sku_model -> stock){
           self::$error = '亲，不能购买更多了!';
           return false;
       }

       $cart_model -> amount += 1;
       $cart_model -> save();
       return true;
    }

    /**购物车的减少
     * @param $uid  int  用户id
     * @param $sku_id  int sku_id
     * @return bool 布尔值
     */
    public function api_decrement($uid,$sku_id)
    {
        $cart_model = self::query()->where('user_id','=',$uid)->where('sku_id','=',$sku_id)->first();
        $sku_model = Product::find($sku_id);
        if(empty($cart_model) || empty($sku_model)){
            return true;
        }

        #检车库存
        if($cart_model-> amount - 1 <= 0){
            self::$error = '已经到底了';
            return false;
        }

        $cart_model -> amount -= 1;
        $cart_model -> save();
        return true;
    }

    /**用户购物车商品的删除
     * @param $uid
     * @param $postData
     * @return bool|null|void
     */
    public function api_delete($uid,$sku_id_list)
    {
        self::query()
             -> where('user_id','=',$uid)
             -> whereIn('sku_id',$sku_id_list)
             -> delete();
        return true;
    }

    /**公共join
     * products表 sku_props_vals表 props表 props_val表 goods_image表
     * @param $query \Illuminate\Database\Eloquent\Builder
     * @param $tableName string 表名
     * @return $query \Illuminate\Database\Eloquent\Builder
     */
    public function _sku_info_join($query=null,$tableName=false)
    {
        if(is_object($tableName)){
            $query = $tableName;
            $tableName = 'products';
        }else{
            $query = $tableName == 'products' ? Product::query() : $query -> leftJoin('products','products.product_id','=',$this->table.'.sku_id') ;
        }

        $spu_id_alias = $tableName == 'products' ? 'goods_id' : 'spu_id';
        $sku_id_alias = $tableName == 'products' ? 'product_id' : 'sku_id';
        return $query
                -> leftJoin('goods_image','goods_image.goods_id','=',$tableName.'.'.$spu_id_alias)
                -> leftJoin('sku_props_vals','sku_props_vals.sku_id','=',$tableName.'.'.$sku_id_alias)
                -> leftJoin('props','props.props_id','=','sku_props_vals.props_id')
                -> leftJoin('props_vals','props_vals.props_val_id','=','sku_props_vals.props_val_id')
                -> where('is_default','=',1);
//                -> where('sku_props_vals.disabled','=',0)
//                -> where('products.disabled','=',0);
    }

    /**用于购物车列表,立即结算和购物车结算页面的商品sku信息列表的返回
     * @param $list   array  需要格式化的列表
     * @$payload      array  需要添加到数组中的参数
     * @return mixed  返回格式化好的列表
     */
    public function _pretty_sku_info_data($list,$is_operate=true)
    {
        #处理规格
        $cart_list = [];

        foreach($list as $cart){
            if(!isset($cart_list[$cart['sku_id']])){
                $cart_list[$cart['sku_id']] = $cart;
            }
            $cart_list[$cart['sku_id']]['props'][] = [
                'props_val_name'=> $cart['props_val_name'],
                'props_val_id'  => $cart['props_val_id'],
                'props_name'    => $cart['props_name'],
                'props_id'      => $cart['props_id'],
            ];

            unset($cart_list[$cart['sku_id']]['props_val_name'],$cart_list[$cart['sku_id']]['props_val_id'],$cart_list[$cart['sku_id']]['props_name'],$cart_list[$cart['sku_id']]['props_id']);

            #如果购物车的数量已经大于商品库存，则将改数量变为库存
            if($cart_list[$cart['sku_id']]['amount'] > $cart_list[$cart['sku_id']]['stock']){
                if(!$is_operate){
                   //则需要抛出库存不足的提示
                   self::$error = '商品:'.$cart_list[$cart['sku_id']]['name'].'选购数量超出库存';
                   return false;
                }

                $cart_list[$cart['sku_id']]['amount'] = $cart_list[$cart['sku_id']]['stock'];
                if(isset($cart_list[$cart['sku_id']]['cart_id'])){
                    $cart_model = self::query()->find($cart_list[$cart['sku_id']]['cart_id']);
                    if(!empty($cart_model)){
                        $cart_model -> amount = $cart_list[$cart['sku_id']]['stock'];
                        $cart_model -> save();
                    }
                }
            }

            #如果商品库存为0，则将清除该购物车中的商品
            if($cart_list[$cart['sku_id']]['stock'] == 0){
                //如果库存为0，则清除该sku
                if(!$is_operate){
                    //则需要抛出库存不足的提示
                    self::$error = '商品:'.$cart_list[$cart['sku_id']]['name'].'库存为0';
                    return false;
                }
                unset($cart_list[$cart['sku_id']]);
            }
        }

        return array_values($cart_list);
    }

    /**
     * 如果订单商品来源于购物车，则当生成订单后，将购物车中的商品清除
     * @param $goodsArr array 形如[['amount'=>1,'sku_id'=>2],['amount'=>22,'sku_id'=>3]]
     */
    public function deleteFromCartWhenMakeOrder($goodsArr,$user_id)
    {
        $sku_id_arr = array_column($goodsArr,'sku_id');
        if(empty($sku_id_arr)){
            return true;
        }

        self::query()->where('user_id','=',$user_id)->whereIn('sku_id',$sku_id_arr)->delete();
        return true;
    }
}
